﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.MessengerConnectHelper;
using System.Net;
using System.Xml;
using HgCo.WindowsLive.SkyDrive;
using System.Threading;
namespace PC2Phone
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Test();
        }
        private static readonly Uri LogOnUri = new Uri("http://login.live.com/login.srf?wa=wsignin1.0&rpsnv=11&ct=1277110668&rver=5.5.4177.0&wp=MBI&wreply=http:%2F%2Fskydrive.live.com%2Fhome.aspx&lc=1033&id=250206&cbcxt=sky");

        NotificationService.Service1Client client = new NotificationService.Service1Client();
        string ChannerUri = "";

        private MessengerConnectSigninContext user1 = null;
        MessengerConnectSigninContext helperForUser1 = new MessengerConnectSigninContext();

        private void FilesDropBox_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                //ChannerUri= client.GetChannelUri(lblcid.Text.ToLower());
                if (client.GetChannelUri(lblcid.Text.ToLower()) != "")
                {
                    if (e.Data.GetDataPresent(DataFormats.FileDrop))
                    {

                        string[] droppedFilePaths = e.Data.GetData(DataFormats.FileDrop, true) as string[];
                        foreach (string droppedFilePath in droppedFilePaths)
                        {
                            SavetoDirectory(droppedFilePath);
                        }

                    }
                    if (e.Data.GetDataPresent(DataFormats.Text))
                    {

                        string message = e.Data.GetData(DataFormats.Text).ToString();

                        if ((message.Contains("http://") || message.Contains("https://")) && (message.Substring(0, 4) == "http"))
                        {
                            SendMessage(message, "link");
                            FilesDropBox.Items.Add(message);
                        }
                        else { FilesDropBox.Items.Add("Please Drag only Files/Links"); }

                    }
                }
                else
                {
                    MessageBox.Show("Please SignIn With Windows LivId In Phone Application");

                }
            }
            catch (Exception)
            {
                ApplicationExceptions.logException("Exception in FilesDropped Method", "PC2Phone", "lblLiveId.Text");
            }

        }

        private void FilesDropBox_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop) || e.Data.GetDataPresent(DataFormats.Text))
                e.Effect = DragDropEffects.Copy;
        }

        private void AddressDropBox_DragEnter(object sender, DragEventArgs e)
        {

            if (e.Data.GetDataPresent(DataFormats.Text))
                e.Effect = DragDropEffects.Copy;
        }

        private void AddressDropBox_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                if (client.GetChannelUri(lblcid.Text.ToLower()) != "")
                {

                    if (e.Data.GetDataPresent(DataFormats.Text))
                    {

                        string message = e.Data.GetData(DataFormats.Text).ToString();
                        SendMessage(message, "address");
                        AddressDropBox.Items.Add(message);
                    }
                    else { AddressDropBox.Items.Add("Please Drag valid Address"); }
                }
                else
                {
                    MessageBox.Show("Please SignIn With Windows LivId In Phone Application");
                }
            }
            catch (Exception)
            {
                ApplicationExceptions.logException("Exception in AddressDropped Method", "PC2Phone", "lblLiveId.Text");
            }
        }

        void SendMessage(string message, string type)
        {
            try
            {
                bool IsliveidRegistred = false;
                string liveId = lblcid.Text.ToLower();
                string username = "admin_" + lblcid.Text.ToLower();
                client.SavetoFile(new byte[0], message, "", username, type, "http://pc2pservice.lartsoft.com/", liveId);
            }
            catch (Exception)
            {
                ApplicationExceptions.logException("Exception in SendMessage Method", "PC2Phone", "lblLiveId.Text");
            }

        }

        void SavetoDirectory(string filePath)
        {
            try
            {
                bool IsliveidRegistred = false;
                string liveId = lblcid.Text.ToLower();
                string fname = System.IO.Path.GetFileName(filePath);
                string dest = System.IO.Path.GetFullPath("Files").Remove(System.IO.Path.GetFullPath("Files").LastIndexOf("bin\\Debug\\Files")) + "Files\\" + fname;

                FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                byte[] mystream = new byte[fs.Length];
                fs.Read(mystream, 0, Convert.ToInt32(fs.Length));
                bool isFile = File.Exists(filePath);
                if (isFile)
                    File.Copy(filePath, dest, true);
                string fileExtension = System.IO.Path.GetExtension(filePath);
                string username = "admin_" + lblcid.Text.ToLower();

                if ((fileExtension.ToLower() == ".jpg") || (fileExtension.ToLower() == ".png") || (fileExtension.ToLower() == ".gif") || (fileExtension.ToLower() == ".jpeg"))
                    client.SavetoFile(mystream, "", fname, username, "image", "http://pc2pservice.lartsoft.com/", liveId);
                else if ((fileExtension.ToLower() == ".mp3") || (fileExtension.ToLower() == ".3gp"))
                    client.SavetoFile(mystream, "", fname, username, "audio", "http://pc2pservice.lartsoft.com/", liveId);

                else if (fileExtension.ToLower() == ".wmv" || fileExtension.ToLower() == ".asf" || fileExtension.ToLower() == ".wma" || fileExtension.ToLower() == ".wm")
                    client.SavetoFile(mystream, "", fname, username, "video", "http://pc2pservice.lartsoft.com/", liveId);
                else
                    client.SavetoFile(mystream, "", fname, username, "other", "http://pc2pservice.lartsoft.com/", liveId);
                FilesDropBox.Items.Add(fname);
            }
            catch (Exception)
            {

                ApplicationExceptions.logException("Exception in SavetoDirectory Method", "PC2Phone", "lblLiveId.Text");

            }

        }

        private void PhoneDropBox_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                if (client.GetChannelUri(lblcid.Text.ToLower()) != "")
                {
                    if (e.Data.GetDataPresent(DataFormats.Text))
                    {
                        string message = e.Data.GetData(DataFormats.Text).ToString();
                        SendMessage(message, "phone");
                        PhoneDropBox.Items.Add(message);

                    }
                    else { PhoneDropBox.Items.Add("Please Drag valid PhoneNumber"); }
                }
                else
                {
                    MessageBox.Show("Please SignIn With Windows LivId In Phone Application");
                }
            }
            catch (Exception)
            {
                ApplicationExceptions.logException("Exception in PhnoDropped Method", "PC2Phone", "lblLiveId.Text");
            }
        }

        private void PhoneDropBox_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.Text))
                e.Effect = DragDropEffects.Copy;
        }

        private void ContentDropBox_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                if (client.GetChannelUri(lblcid.Text.ToLower()) != "")
                {
                    if (e.Data.GetDataPresent(DataFormats.Text))
                    {
                        string message = e.Data.GetData(DataFormats.Text).ToString();
                        SendMessage(message, "text");
                        ContentDropBox.Text = message;

                    }
                    else { PhoneDropBox.Items.Add("Please Drag valid PhoneNumber"); }
                }
                else
                {
                    MessageBox.Show("Please SignIn With Windows LivId In Phone Application");
                }
            }
            catch (Exception)
            {
                ApplicationExceptions.logException("Exception in PhnoDropped Method", "PC2Phone", "lblLiveId.Text");
            }
        }

        private void ContentDropBox_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.Text))
                e.Effect = DragDropEffects.Copy;
        }

        private void btnSignIn_Click(object sender, EventArgs e)
        {
            try
            {
                helperForUser1.SignInCompleted += new MessengerConnectSigninContext.SignInCompletedEventHandler(MessengerConnectSigninHelper_SignInCompleted);
                helperForUser1.GetTokenAsync("000000004804274D", "HcjYK1IHLA8HyCdG2JwGtCjjs1tokmrD", new Object());
            }
            catch (Exception)
            {
                ApplicationExceptions.logException("Exception in btnSignIn_Click Method", "PC2Phone", "lblLiveId.Text");
            }

        }

        void MessengerConnectSigninHelper_SignInCompleted(SignInCompletedEventArgs e)
        {
            try
            {
                if (e.Succeeded)
                {
                    SkyDriveWebClient wcSkyDrive = new SkyDriveWebClient();
                    GetProfileUri("http://apis.live.net/v4.1/");
                    pnldropboxes.Visible = true;
                    btnSignIn.Visible = false;
                   
                    wcSkyDrive.LogOn("vvgopal@lartsoft.com", "gopala");

                   // Thread.Sleep(100000);
                 WebDriveInfo wdinfo= wcSkyDrive.GetWebDriveInfo();
                 lbltotalspace.Text = "Total Avialble Space:" + wdinfo.FreeDiskSpace.ToString();
                 lblusedSpace.Text = "Used Space:" + wdinfo.UsedDiskSpace.ToString();
                 //lblunusedspace.Text = "Free Space:" + (Convert.ToDouble(wdinfo.FreeDiskSpace) - Convert.ToDouble(wdinfo.UsedDiskSpace)).ToString();
                 WebFolderInfo[] wpinfo = wcSkyDrive.ListRootWebFolders(); 
                }
            }
            catch (Exception ex) 
            {
                ApplicationExceptions.logException("Exception in MessengerConnectSigninHelper_SignInCompleted Method", "PC2Phone", "lblLiveId.Text");
            }
        }

        void GetProfileUri(string uri)
        {

            Uri someUri = new Uri(uri);
            HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(someUri);
            webRequest.Method = "GET";
            webRequest.Headers[MessengerConnectConstants.AuthorizationHeader] = helperForUser1.AuthorizationToken;
            webRequest.BeginGetResponse(
                new AsyncCallback(HandleWebResponse), webRequest);

        }

        private void HandleWebResponse(IAsyncResult result)
        {
            try
            {
                HttpWebRequest webRequest = result.AsyncState as HttpWebRequest;
                HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(result);

                StreamReader responseStreamReader = new StreamReader(webResponse.GetResponseStream());
                String response = responseStreamReader.ReadToEnd();
                XmlDocument xdoc = new XmlDocument();
                xdoc.LoadXml(response);

                XmlNodeList profile = xdoc.GetElementsByTagName("Uri");
                XmlNodeList ContactInfo = xdoc.GetElementsByTagName("p3:Address");
                if (profile.Count != 0)
                {
                    GetProfileUri(profile[0].InnerText);
                    string test = profile[0].ChildNodes[0].InnerText.ToString();
                    Invoke(new UpdateLabelFieldDelegate(UpdateLabelField), test);

                }
                if (ContactInfo.Count != 0)
                {
                    string test = ContactInfo[0].InnerText.ToString();
                    Invoke(new UpdateTextFieldDelegate(UpdateTextField), test);
                }



            }
            catch (Exception)
            {
                ApplicationExceptions.logException("Exception in HandleWebResponse Method", "PC2Phone", "lblLiveId.Text");
            }
        }

        delegate void UpdateTextFieldDelegate(String newText);

        private void UpdateTextField(String liveId)
        {
            lblLiveId.Text = liveId;
            label6.Visible = true;
            string ChannerUri = client.GetChannelUri(liveId);

        }

        delegate void UpdateLabelFieldDelegate(String newText);

        private void UpdateLabelField(String someText)
        {
            string[] strarray = someText.Split('/');
            string[] str = strarray[4].Split('-');
            lblcid.Text = str[1].ToString();
        }

        private void FilesPasteMenuItem_Click(object sender, System.EventArgs e)
        {
            if (FilesDropBox.SelectedIndex != -1)
            {
                try
                {
                    if (client.GetChannelUri(lblcid.Text.ToLower()) != "")
                    {
                        IDataObject data = Clipboard.GetDataObject();
                        if (!data.GetDataPresent(DataFormats.FileDrop))
                            return;

                        string[] files = (string[])data.GetData(DataFormats.FileDrop);
                        MemoryStream stream = (MemoryStream)data.GetData("Preferred DropEffect", true);
                        int flag = stream.ReadByte();
                        if (flag != 2 && flag != 5)
                            return;
                        foreach (string file in files)
                        {
                            SavetoDirectory(file);
                        }
                    }
                    else
                    {
                        MessageBox.Show("Please SignIn With Windows LivId In Phone Application");
                    }
                }
                catch (Exception)
                {
                    ApplicationExceptions.logException("Exception in FilesPasteMenuItem_Click Method", "PC2Phone", "lblLiveId.Text");
                }
            }
            else
            {
                MessageBox.Show("Please select an item", "Context Menu Tester", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

            }
        }

        private void AddrPasteMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (client.GetChannelUri(lblcid.Text.ToLower()) != "")
                {
                    IDataObject data = Clipboard.GetDataObject();
                    if (!data.GetDataPresent(DataFormats.Text))
                        return;
                    string message = (string)data.GetData(DataFormats.Text);

                    SendMessage(message, "address");
                    AddressDropBox.Items.Add(message);
                }
                else
                {
                    MessageBox.Show("Please SignIn With Windows LivId In Phone Application");
                }

            }
            catch (Exception)
            {
                ApplicationExceptions.logException("Exception in AddrPasteMenuItem_Click Method", "PC2Phone", "lblLiveId.Text");
            }
        }

        private void PhonePasteMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (client.GetChannelUri(lblcid.Text.ToLower()) != "")
                {
                    IDataObject data = Clipboard.GetDataObject();
                    if (!data.GetDataPresent(DataFormats.Text))
                        return;
                    string message = (string)data.GetData(DataFormats.Text);

                    SendMessage(message, "phone");
                    PhoneDropBox.Items.Add(message);
                }
                else
                {
                    MessageBox.Show("Please SignIn With Windows LivId In Phone Application");
                }
            }
            catch (Exception)
            {
                ApplicationExceptions.logException("Exception in PhonePasteMenuItem_Click Method", "PC2Phone", "lblLiveId.Text");
            }
        }

        private void FilesDeleteMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string[] files = GetSelection();
                if (files != null)
                {
                    object obj = files[0] as object;
                    FilesDropBox.Items.Remove(obj);
                    IDataObject data = new DataObject(DataFormats.FileDrop, files);
                    Clipboard.SetDataObject(data);
                }
            }
            catch (Exception)
            {
                ApplicationExceptions.logException("Exception in FilesDeleteMenuItem_Click Method", "PC2Phone", "lblLiveId.Text");
            }
        }

        private void AddrDeleteMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (AddressDropBox.SelectedItems.Count != 0)
                {
                    foreach (string item in AddressDropBox.SelectedItems)
                    {
                        AddressDropBox.Items.Remove(item);
                        IDataObject data = new DataObject(DataFormats.Text, item);
                        Clipboard.SetDataObject(data);

                    }
                }
            }
            catch (Exception)
            {
                ApplicationExceptions.logException("Exception in AddrDeleteMenuItem_Click Method", "PC2Phone", "lblLiveId.Text");
            }
        }

        private void PhoneDeleteMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (string item in PhoneDropBox.SelectedItems)
                {
                    PhoneDropBox.Items.Remove(item);
                    IDataObject data = new DataObject(DataFormats.Text, item);
                    Clipboard.SetDataObject(data);

                }
            }
            catch (Exception ex)
            {
                ApplicationExceptions.logException("Exception in PhoneDeleteMenuItem_Click Method", "PC2Phone", "lblLiveId.Text");

            }
        }

        private string[] GetSelection()
        {

            if (FilesDropBox.SelectedItems.Count == 0)
                return null;

            string[] files = new string[FilesDropBox.SelectedItems.Count];
            int i = 0;
            foreach (string item in FilesDropBox.SelectedItems)
            {
                files[i++] = item.ToString();
            }
            return files;


        }

        void Test()
        {
            WebClient webClient = new WebClient();
            string s = webClient.DownloadString(LogOnUri);
           //LogOn();
        }
        void LogOn()
        {
            SkyDriveWebClient wcSkyDrive = new SkyDriveWebClient();
            //wcSkyDrive.Session.Reset();
           // wcSkyDrive.LogOn("vvgopal@lartsoft.com", "gopala");
           
            //string s = wcSkyDrive.Session.Cid;
            WebFolderItemInfo[] rootWebFolders=new WebFolderItemInfo[]{};
            // this line is generating error
            rootWebFolders = wcSkyDrive.ListRootWebFolderItems();
            //List<WebFolderItemInfo> list = rootWebFolders.ToList();
            
        }

    }
}
